<?php
namespace app\controller;

use app\BaseController;
use think\Request;
use think\facade\Log;
use app\service\{
    ChatService,
    AiChatService,
    AiService,
    AiTeachingService
};
use app\model\{ChatSession, ChatMessage};
use Exception;

class ChatController extends BaseController
{
    protected $chatService;
    protected $aiChatService;
    protected $aiTeachingService;

    public function __construct()
    {
        $this->chatService = new ChatService();
        $this->aiChatService = new AiChatService();
        $this->aiTeachingService = new AiTeachingService();
    }

    /**
     * 获取会话列表
     */
    public function sessions(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $type = $request->param('type');
        $page = $request->param('page', 1);
        $pageSize = $request->param('page_size', 10);

        $sessions = $this->chatService->getUserSessions($user, $type, $page, $pageSize);

        return json([
            'status' => 200,
            'data' => [
                'total' => $sessions->total(),
                'current_page' => $sessions->currentPage(),
                'last_page' => $sessions->lastPage(),
                'sessions' => $sessions->items()
            ]
        ]);
    }

    /**
     * 创建新会话
     */
    public function createSession(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        try {
            $session = $this->chatService->createSession($user, $request->post());

            return json([
                'status' => 200,
                'message' => '会话创建成功',
                'data' => $session
            ]);
        } catch (Exception $e) {
            return json(['status' => 500, 'message' => '创建失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取会话消息
     */
    public function messages(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        try {
            $messages = $this->chatService->getSessionMessages(
                $request->param('session_id'),
                $user,
                $request->param('page', 1),
                $request->param('page_size', 20)
            );

            return json([
                'status' => 200,
                'data' => [
                    'total' => $messages->total(),
                    'current_page' => $messages->currentPage(),
                    'last_page' => $messages->lastPage(),
                    'messages' => $messages->items()
                ]
            ]);
        } catch (Exception $e) {
            return json(['status' => 404, 'message' => $e->getMessage()]);
        }
    }

    /**
     * 发送消息
     */
    public function sendMessage(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        try {
            $message = $this->chatService->sendMessage(
                $request->post('session_id'),
                $user,
                $request->post('content'),
                $request->post('type', ChatMessage::TYPE_TEXT)
            );

            return json([
                'status' => 200,
                'message' => '消息发送成功',
                'data' => $message
            ]);
        } catch (Exception $e) {
            return json(['status' => 500, 'message' => '发送失败：' . $e->getMessage()]);
        }
    }

    /**
     * 删除会话
     */
    public function deleteSession(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        try {
            $session = ChatSession::where('id', $request->param('session_id'))
                ->where('user_id', $user->id)
                ->findOrFail();
                
            $session->delete();
            return json(['status' => 200, 'message' => '会话删除成功']);
        } catch (Exception $e) {
            return json(['status' => 500, 'message' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * AI聊天请求
     * 根据前端是否提交会话id  判断当前聊天是否需要准备历史会话上下文
     * 如果前端没给session_id  则生成一个会话记录 并返回会话id
     * 如果前端给了session_id  则根据session_id 查询会话记录 并返回会话历史
     */
    public function aiChat(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        try {
            $result = $this->aiChatService->handleChatRequest(
                $user,
                $request->post('content'),
                $request->post('session_id', 0)
            );

            return json([
                'status' => 200,
                'message' => '请求已接受',
                'data' => $result
            ]);
        } catch (Exception $e) {
            return json(['status' => 500, 'message' => '请求失败：' . $e->getMessage()]);
        }
    }

    /**
     * AI流式响应
     */
    public function aiStream(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        try {
            header('Content-Type: text/event-stream');
            header('Cache-Control: no-cache');
            header('X-Accel-Buffering: no');
            
            $result = $this->aiChatService->handleStreamResponse(
                $request->param('message_id'),
                $user
            );

            $aiService = new AiService();
            $fullContent = '';
            
            // 调用AI大模型接口进行流式对话
            $aiService->streamChat($result['history'], function($chunk) use (&$fullContent) {
                $fullContent .= $chunk;
                echo "data: " . json_encode([
                    'content' => $chunk, 
                    'done' => false
                ]) . "\n\n";
                ob_flush();
                flush();
            }, $result['sessionInfo']);

            // 保存完整的AI回复内容
            $result['aiMessage']->content = $fullContent;
            $result['aiMessage']->save();
            
            echo "data: " . json_encode([
                'content' => '',
                'done' => true
            ]) . "\n\n";
            
        } catch (Exception $e) {
            echo "data: " . json_encode([
                'error' => $e->getMessage(),
                'done' => true
            ]) . "\n\n";
        }
    }

    /**
     * AI JSON格式流式响应
     */
    public function aiJsonStream(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        try {
            header('Content-Type: text/event-stream');
            header('Cache-Control: no-cache');
            header('X-Accel-Buffering: no');
            
            $result = $this->aiChatService->handleStreamResponse(
                $request->param('message_id'),
                $user
            );

            // Log::debug('AI流式响应处理结果：' . json_encode( [
            //     'message_id' => $request->param('message_id'),
            //     'history_count' => count($result['history'] ?? []),
            //     'session_info' => $result['sessionInfo'] ?? null
            // ], JSON_UNESCAPED_UNICODE));

            $aiService = new AiService();
            $fullContent = '';
            
            $aiService->streamChat($result['history'], function($chunk) use (&$fullContent, $result) {
                $fullContent .= $chunk;
                
                
                echo "data: " . json_encode([
                    'content' => $chunk,
                    'done' => false
                ], JSON_UNESCAPED_UNICODE) . "\n\n";
                
                ob_flush();
                flush();
            }, $result['sessionInfo']);
            $result['aiMessage']->content = $fullContent;
            $result['aiMessage']->save();
            echo "data: " . json_encode([
                'content' => '',
                'done' => true
            ]) . "\n\n";
            
        } catch (Exception $e) {
            Log::error('AI流式响应失败：'. json_encode([
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'request_params' => $request->param()
            ], JSON_UNESCAPED_UNICODE));
            
            echo "data: " . json_encode([
                'error' => $e->getMessage(),
                'done' => true
            ]) . "\n\n";
        }
    }

    /**
     * 将笔记转换为教案
     */
    public function convertNoteToTeachingPlan(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $note = $request->post('note');
        if (empty($note)) {
            return json(['status' => 400, 'message' => '笔记内容不能为空']);
        }

        try {
            \think\facade\Log::debug('开始笔记转教案：', [
                'user_id' => $user->id,
                'note_length' => strlen($note)
            ]);
            
            $teachingPlan = $this->aiTeachingService->convertNoteToTeachingPlan($note);
            
            \think\facade\Log::info('笔记转教案成功：', [
                'user_id' => $user->id,
                'elements_count' => count($teachingPlan)
            ]);
            
            return json([
                'status' => 200,
                'message' => '转换成功',
                'data' => [
                    'teaching_plan' => $teachingPlan,
                    'statistics' => [
                        'total_elements' => count($teachingPlan),
                        'lecture_count' => count(array_filter($teachingPlan, fn($e) => $e['type'] === 'lecture')),
                        'question_count' => count(array_filter($teachingPlan, fn($e) => $e['type'] === 'question'))
                    ]
                ]
            ]);
            
        } catch (Exception $e) {
            \think\facade\Log::error('笔记转教案失败：', [
                'user_id' => $user->id,
                'error' => $e->getMessage()
            ]);
            
            return json([
                'status' => 500,
                'message' => '转换失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 课程学习会话请求
     * 处理课程或教案的学习会话，包括进度记录生成、恢复和聊天上下文还原
     * @param Request $request
     * @return \think\response\Json
     */
    public function learningChat(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        try {
            $courseId = $request->post('course_id', 0);
            $teachingPlanId = $request->post('teaching_plan_id', 0);
            
            if (!$courseId && !$teachingPlanId) {
                return json(['status' => 400, 'message' => '请提供课程ID或教案ID']);
            }

            $result = $this->aiChatService->handleLearningChatRequest(
                $user,
                $courseId,
                $teachingPlanId
            );

            return json([
                'status' => 200,
                'message' => '请求已接受',
                'data' => $result
            ]);
        } catch (Exception $e) {
            return json(['status' => 500, 'message' => '请求失败：' . $e->getMessage()]);
        }
    }
} 